package com.keke.beauty.auth.activityInvolvement.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.keke.beauty.auth.activity.entity.TabActivity;
import com.keke.beauty.auth.activity.mapper.TabActivityMapper;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.keke.beauty.auth.activityInvolvement.entity.TabActivityInvolvement;
import com.keke.beauty.auth.activityInvolvement.entity.TabIntegralsFlow;
import com.keke.beauty.auth.activityInvolvement.mapper.TabActivityInvolvementMapper;
import com.keke.beauty.auth.activityInvolvement.mapper.TabIntegralsFlowMapper;
import com.keke.beauty.auth.activityInvolvement.service.TabActivityInvolvementService;
import com.keke.beauty.sys.wxUser.entity.TabWxUser;
import com.keke.beauty.sys.wxUser.mapper.TabWxUserMapper;
import com.keke.beauty.utils.exception.RRException;

/**
 * 描述：活动参与服务层
 *
 * @author
 * @Data 2019年02月27日 11:06:36
 */
@Service
public class TabActivityInvolvementServiceImpl implements TabActivityInvolvementService {

    /**
     * 点赞获取
     */
    private final static int INTEGRALSNUM = 10;

    @Autowired
    private TabActivityInvolvementMapper mapper;

    @Autowired
    private TabIntegralsFlowMapper tntegralsFlowMapper;

    @Autowired
    private TabWxUserMapper wxUserMapper;

    @Autowired
    private TabActivityMapper activityMapper;

    /**
     * 根据guid查询活动参与
     *
     * @param id
     * @return
     * @author
     * @Data 2019年02月27日 11:06:36
     */
    @Override
    public TabActivityInvolvement findByPrimaryKey(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    /**
     * 保存活动参与
     *
     * @param activityInvolvement
     * @return
     * @author
     * @Data 2019年02月27日 11:06:36
     */
    @Override
    public Integer insert(TabActivityInvolvement activityInvolvement) {
        return mapper.insertSelective(activityInvolvement);
    }

    /**
     * 更新活动参与
     *
     * @param activityInvolvement
     * @return
     * @author
     * @Data 2019年02月27日 11:06:36
     */
    @Override
    public Integer update(TabActivityInvolvement activityInvolvement) {
        return mapper.updateByPrimaryKeySelective(activityInvolvement);
    }

    /**
     * 活动参与列表
     *
     * @param search
     * @return
     * @author
     * @Data 2019年02月27日 11:06:36
     */
    @Override
    public List<TabActivityInvolvement> getList(String search) {
        return mapper.selectAll(search);
    }

    /**
     * 功能描述：分享浏览网页
     * 创建时间：2019年2月27日 下午2:35:22
     *
     * @param openId
     * @param referralsOpenId
     */
    @Override
    @Transactional
    public void salute(String openId, int activityId, String referralsOpenId, String username, String phone) {
        TabActivityInvolvement tabActivityInvolvement = new TabActivityInvolvement();
        tabActivityInvolvement.setOpenid(openId);
        tabActivityInvolvement.setActivityId(activityId);
        TabActivityInvolvement activityInvolvement = mapper.selectByOpenId(tabActivityInvolvement);
        if (StringUtils.isEmpty(activityInvolvement)) {
            throw new RRException("你是非法用户！");
        }
        if (!StringUtils.isEmpty(referralsOpenId) && !referralsOpenId.equals(openId)&&!referralsOpenId.equals("null")) {
            Integer count = tntegralsFlowMapper.countNumByOpenIdAndActivityAndReferras(openId, activityId,referralsOpenId);
            if (count == 0) {
                TabActivity activity = activityMapper.selectByPrimaryKey(activityId);
                TabActivityInvolvement param = new TabActivityInvolvement();
                param.setOpenid(referralsOpenId);
                param.setActivityId(activityId);
                TabActivityInvolvement data = mapper.selectByOpenId(param);
                data.setIntegrals(data.getIntegrals() + (activity.getIntegralRule()/2));
                mapper.updateByPrimaryKeySelective(data);
            }
        }
        addIntegrals(openId, activityId, 0, username, phone, referralsOpenId);
    }

    /**
     * 功能描述：
     * 作者：张进
     *
     * @param openId
     * @param activityId
     * @param type
     */
    public void addIntegrals(String openId, int activityId, int type, String username, String phone, String referralsOpenId) {
        TabIntegralsFlow integralsFlow = new TabIntegralsFlow();
        integralsFlow.setActivityId(activityId);
        integralsFlow.setOpenId(openId);
        integralsFlow.setReferrals(referralsOpenId);
        integralsFlow.setCreateTime(new Date());
        integralsFlow.setRemark(type == 0 ? "浏览活动" : "分享活动" );
        integralsFlow.setType((short) type);
        integralsFlow.setUsername(username);
        integralsFlow.setPhone(phone);
        tntegralsFlowMapper.insertSelective(integralsFlow);
    }

    /**
     * 功能描述：
     * 作者：张进
     * 创建时间：2019年2月27日 下午4:02:34
     *
     * @param name
     * @param phone
     * @param openId
     */
    @Override
    public void signUp(String name, String phone, String openId, Integer activityId) {
        TabActivityInvolvement tabActivityInvolvement = new TabActivityInvolvement();
        tabActivityInvolvement.setOpenid(openId);
        tabActivityInvolvement.setActivityId(activityId);
        TabActivityInvolvement activityInvolvement = mapper.selectByOpenId(tabActivityInvolvement);
        if (StringUtils.isEmpty(activityInvolvement)) {
            throw new RRException("你是非法用户！");
        }
        TabActivity activity = activityMapper.selectByPrimaryKey(activityId);
        activityInvolvement.setIntegrals(activityInvolvement.getIntegrals()+activity.getIntegralRule());
        activityInvolvement.setUsername(name);
        activityInvolvement.setPhone(phone);
        activityInvolvement.setIsSignUp((short) 1);
        activityInvolvement.setSignUpTime(new Date());
        mapper.updateByPrimaryKeySelective(activityInvolvement);

        // 更新手机号
        TabWxUser wxUser = new TabWxUser();
        wxUser.setOpenid(openId);
        wxUser.setPhone(phone);
        wxUserMapper.updateByPrimaryKeySelective(wxUser);
    }

    /**
     * 功能描述：
     * 作者：张进
     * 创建时间：2019年2月27日 下午9:21:15
     *
     * @param activityInvolvement
     * @return
     */
    @Override
    public Map<String, Object> selectByOpenIdAndActivityId(TabActivityInvolvement activityInvolvement) {
        return mapper.selectByOpenIdAndActivityId(activityInvolvement);
    }

    /**
     * 功能描述：
     * 作者：张进
     * 创建时间：2019年2月28日 上午11:17:06
     *
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> findSingUpList(Integer id) {
        return mapper.findSingUpList(id);
    }

    /**
     * 功能描述：
     * 作者：张进
     * 创建时间：2019年2月28日 下午2:19:01
     *
     * @param search
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> getList(String search, Integer id, String isSignUp) {
        return mapper.getList(search, id, isSignUp);
    }

    /**
     * 功能描述：
     * 作者：张进
     * 创建时间：2019年2月28日 下午3:28:13
     *
     * @param search
     * @param id
     * @throws IOException
     */
    @Override
    public void downloadExcel(OutputStream out, String search, Integer id, String isSignUp) throws IOException {
        List<Map<String, Object>> list = null;
        if (id == null) {
            list = new ArrayList<>();
        } else {
            list = mapper.getList(search, id, isSignUp);
        }
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        createTitle(sheet.createRow(0));

        insertDataToExcel(sheet, list);
        workbook.write(out);
    }

    /**
     * 功能描述：导出插入数据
     * 创建时间：2019年2月28日 下午3:37:08
     *
     * @param sheet
     * @param list
     */
    private void insertDataToExcel(XSSFSheet sheet, List<Map<String, Object>> list) {
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(getStr(map, "name"));
            row.createCell(1).setCellValue(getStr(map, "nickname"));
            row.createCell(2).setCellValue(getStr(map, "username"));
            row.createCell(3).setCellValue(getStr(map, "phone"));
            row.createCell(4).setCellValue(getInteger(map, "integrals"));
            row.createCell(5).setCellValue(getStr(map, "referralsNickname"));
            row.createCell(6).setCellValue(getStr(map, "referralsPhone"));
            row.createCell(7).setCellValue(getStr(map, "signUpTime"));
        }
    }

    private Integer getInteger(Map<String, Object> map, String key) {
        String str = getStr(map, key);
        return Integer.valueOf(str);
    }

    private String getStr(Map<String, Object> map, String key) {
        Object obj = map.get(key);
        return null == obj ? "" : obj.toString();
    }

    /**
     * 功能描述：创建excel表头
     * 创建时间：2019年2月28日 下午3:29:28
     *
     * @param createRow
     */
    private void createTitle(Row row) {
        String[] titles = {"活动名称", "昵称", "姓名", "电话号码", "积分数量", "推荐人", "推荐人电话",  "报名时间"};
        Cell cell = null;
        for (int i = 0; i < titles.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(titles[i]);
        }
    }

}